#include "clientsocket.h"
#include <QDomDocument>
#include <QHostAddress>
#include "commonutils.h"

ClientSocket::ClientSocket(QTcpSocket* soc, QObject*parent):QObject(parent){
    socket=soc;
    connect(socket,SIGNAL(readyRead()),this,SLOT(readyRead()));
    connect(socket, SIGNAL(disconnected()), this, SLOT(deleteLater()));
    cliTimer.setInterval(1000);
    connect(&cliTimer, SIGNAL(timeout()),
            this, SLOT(timeout()));
    cliTimer.start();
};

void ClientSocket::timeout(){
    if(capList.isEmpty())
        return;

    QDomDocument doc("CaptchaSolver");
    QDomElement root = doc.createElement("captchas");
    doc.appendChild(root);
    foreach(CaptchaDesc* cd, capList){
        QDomElement mainTag=doc.createElement("captcha");
        mainTag.setAttribute("action","question");
        //mainTag.appendChild(doc.createElement("action")).toElement().setAttribute("question"));
        mainTag.appendChild(doc.createElement("hash")).
            appendChild(doc.createTextNode(QString().setNum(cd->getHash())));
        mainTag.appendChild(doc.createElement("address")).
            appendChild(doc.createTextNode(cd->getAddress()));
        root.appendChild(mainTag);
    }

    QString xml = doc.toString();

    socket->write(xml.toAscii());
    socket->flush();

    capList.clear();
};


void ClientSocket::question(CaptchaDesc* desc){
    capList.append(desc);
    return;

};

void ClientSocket::readyRead(){
    QDomDocument doc;
    doc.setContent(socket->readAll());


    QDomNodeList list=doc.elementsByTagName("captcha");
    if(list.isEmpty()){
        qDebug()<<"Nie znaleziono tagu captcha";
        return;
    }

    for(unsigned int i=0; i<list.length(); i++){
        QString action(CommonUtils::getSingleAttributeValue(list.at(i), "action"));

        if(action=="answer"){
            //qDebug()<<"Question";
            QString caption(CommonUtils::getSingleTagValue(list.at(i), "caption"));
            QString hash(CommonUtils::getSingleTagValue(list.at(i), "hash"));
            if(hash=="" || caption==""){
                qDebug()<<"problem decoding message "<<list.at(i).toDocument().toString() ;
            }else{
                emit solved(hash.toInt(), caption);
            }
        }else{
            qDebug()<<"Dont understand "<<action<<" action";
        }
    }
}

ClientSocket::~ClientSocket(){
    qDebug()<<"Deleting ClientSocket";
    emit toBeDeleted(this);
    delete socket;
}
